<template>
  <el-card>
    <div slot="header">
      <h3>{{ pageTitle }}</h3>
    </div>
    <div>
      <el-row type="flex" justify="end" v-if="!pageState.view">
        <el-button
          v-if="showBtn('高级关联')"
          type="text"
          size="large"
          icon="el-icon-link"
          @click="handleSeniorAssociated"
        >高级关联</el-button
        >
        <el-button
          v-if="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleAssociatedGoods"
          >关联商品</el-button
        >
        <el-button
          type="text"
          size="large"
          @click="handleExportData"
          :loading="loading.export"
          :disabled="tableData.length === 0"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/update/product/allmanaging/saveAllManagingToPage`"
            ><el-button type="text" size="large">模板导入</el-button></Upload
          ></a
        >
        <el-button
          type="text"
          size="large"
          @click="handleSaveData"
          :loading="loading.submit"
          :disabled="tableData.length === 0"
          >暂存</el-button
        >
        <el-button
          type="text"
          size="large"
          @click="handleSubmitData"
          :loading="loading.submit"
          :disabled="tableData.length === 0"
          >提交</el-button
        >
        <el-button
          v-if="!pageState.menu"
          type="text"
          size="large"
          @click="handleGoBack"
        >返回</el-button>
      </el-row>
      <!-- 发起原因输入框 -->
      <LaunchReasonInput
        :reason.sync="launchReason"
        :isDisabled="pageState.view"
      />
      <el-row class="format_table_wrap">
        <general-render-table
          :loading="loading.table"
          :data-source="tableData"
          :columns="tableColumns"
          @handleCancelSelect="handleCancelSelect"
          @handleChangeRadio="handleChangeRadio"
          @handleChangeCheckBox="handleChangeCheckBox"
        />
      </el-row>
      <!-- 表尾字段 -->
      <FooterFields :footerFields="footerFields" />
    </div>
    <!-- 关联商品-SPU维度弹框 -->
    <SpuAssociatedDialog
      ref="spuModal"
      :columns="associatedGoods.columns"
      :requestApi="associatedGoods.requestApi"
      :requestParams="associatedGoods.requestParams"
      :distinctParams="associatedGoods.distinctParams"
      @getRowList="handleGetTableData"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorAssociated.visible"
      :columns="seniorAssociated.columns"
      :dataSource="seniorAssociated.dataSource"
      @seniorSearchResult="getSeniorResultFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
/* components */
import SpuAssociatedDialog from '@/components/common/dialog/associatedGoods/spuAssociatedDialog';
import GeneralRenderTable from '@/pages/commodity/modules/components/generalRenderTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import LaunchReasonInput from '@/components/LaunchReasonInput';
/* mixins */
import spuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/spuDimension';
/* constants */
import { requiredParams } from '@/components/common/dialog/associatedGoods/constants/spuDimension';
import { EDIT_MANAGE_INFO_AMOUNT } from '@/constants/exportAmountLimit';
/* utils */
import {
  getAttributeTypeFn,
  performDifferentTypeMethodsFn
} from '@/pages/commodity/modules/utils';
import { getDealManageDataToApiFn } from '@/pages/commodity/modules/utils/manageInfoRequireUtils';
import { getAuthDepartmentsFn } from '@/pages/commodity/modules/utils/salePriceRequireUtils';
import { generateHighlightNodeForSalePrice } from '@/utils/bizUtils';
import { getFooterFieldsService } from '@/api/commodity/common';

export default {
  mixins: [spuDimensionMixins],
  components: {
    SpuAssociatedDialog,
    GeneralRenderTable,
    FooterFields,
    SeniorLinkedDialog,
    LaunchReasonInput
  },
  data () {
    return {
      footerFields: {}, // 表尾字段
      launchReason: '', // 发起原因
      seniorAssociated: {
        visible: false,
        isSenior: false, // 是否是高级关联，true是，false为普通关联
        columns: [{
          label: 'SPU编码',
          prop: 'spuNo',
          type: 'textarea'
        }],
        dataSource: [{ spuNo: '' }]
      },
      associatedGoods: {
        requestApi: {
          url: ['/sysback/update/product/allmanaging/getProductList'],
          type: 'post'
        },
        requestParams: requiredParams.requestParams,
        distinctParams: requiredParams.distinctParams,
        columns: [
          { type: 'selection', width: 60, align: 'center' },
          { title: '商品名称', key: 'productName' },
          { title: 'SPU编码', key: 'spuNo' },
          { title: '规格参数', key: 'saleAttrInfo' },
          { title: '品牌', key: 'brandName' },
          { title: '操作', slot: 'action', align: 'center', fixed: 'right' }
        ]
      },
      loading: {
        table: false, // 表格加载loading
        submit: false, // 提交按钮loading
        export: false // 导出按钮loading
      },
      pageState: {
        menu: false, // 菜单
        view: false, // 查看
        edit: false, // 修改
        single_sku: false, // SKU管理
        single_spu: false // SPU管理
      },
      initTableColumns: [
        {
          title: 'SPU编码',
          key: 'spuNo',
          width: 120,
          fixed: 'left'
        },
        {
          title: '商品名称',
          key: 'productNameFinal',
          width: 120,
          fixed: 'left'
        },
        {
          title: '归属部门',
          slot: 'authDepartments',
          align: 'center',
          fixed: 'left',
          render: (h, { row }) => {
            return h('div', getAuthDepartmentsFn(row));
          }
        }
      ],
      tableColumns: [], // 管理信息表格列表字段
      tableData: [], // 列表的数据源
      /**
       * @notShowAttrList 不进行展示的表格字段集合
       * @manage_distributing_centre 集散地
       * @logistics_pack 配送装车方式
       * @logistics_transport 运输特性
       * @logistics_restrict 发货限制
       * @logistics_stock 存量属性
       * @manage_packlist 包装清单
       */
      notShowAttrList: [
        'manage_distributing_centre',
        'logistics_pack',
        'logistics_transport',
        'logistics_restrict',
        'logistics_stock',
        'manage_packlist'
      ],
      conformShowBtnConditions: ['未提交', '审核未通过'], // 暂存按钮或提交按钮是否可显示的条件之一
      notConformShowBtnConditions: ['已提交', '审核中', '审核通过'],
      recordNo: '', // 单据号
      apiSourceList: {
        /* 查询管理信息-- 用单据号查询 */
        queryTableDataFromDocManage: {
          url: '/sysback/product/update/record/queryRecordAllManaging',
          type: 'post'
        },
        /* 查询管理信息---uuid查询_来自SPU查询 */
        queryTableDataFromSpu: {
          url: '/sysback/update/product/allmanaging/queryAllManagingListFromSpu',
          type: 'post'
        },
        /* 查询管理信息---uuid查询_来自SKU查询 */
        queryTableDataFromSku: {
          url: '/sysback/update/product/allmanaging/queryAllManagingListFromSpu',
          type: 'post'
        },
        /* 单据信息-- 根据recordNo查询 */
        getFooterFieldsByRecordNo: {
          url: '/sysback/product/update/record/getByRecordNo',
          type: 'post'
        },
        /* 单据信息-- 根据productUuid查询 */
        getFooterFieldsByUuid: {
          url: '/sysback/product/update/record/queryRecordExist',
          type: 'post'
        },
        /*  查询单据信息---skuNo查询_来自SKU查询 */
        getFooterFieldsBySkuNo: {
          url: '/sysback/product/update/record/queryRecordExistBySku',
          type: 'post'
        }
      },
      apiObj: {
        // 暂存
        saveBasicInfo: {
          url: '/sysback/update/product/allmanaging/saveAllManaging', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 提交
        commitBasicInfo: {
          url: '/sysback/update/product/allmanaging/commitAllManaging', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 导出管理信息
        exportPageToExcelPost: {
          url: '/sysback/update/product/allmanaging/exportPageToExcelPost', // 接口地址
          type: 'post' // 接口请求类型
        }
      }
    };
  },
  watch: {
    '$route.path' (newValue) {
      this.$router.go(0);
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    /* 标题 */
    pageTitle () {
      let title = '修改管理信息';
      let { menu, view } = this.pageState;
      if (menu) {
        return title;
      } // 从菜单修改sku页面进入
      if (view) {
        // 查看页面
        title = `${title}-表单查看页面`;
        return title;
      }
      title = `${title}-表单修改页面`; // 修改页面
      return title;
    }
  },
  mounted () {
    this.initPageDataFn(); // 初始页面数据方法
    this.tableColumns = _.cloneDeep(this.initTableColumns);
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    // 获取字段信息
    async getFieldsInfo (recordNo) {
      if (!recordNo) return
      const retData = await getFooterFieldsService({ recordNo }, '.footer_fields_card');
      if (retData) {
        this.launchReason = retData.launchReason;
        this.footerFields = retData;
      }
    },
    handleGoBack () {
      let routeName = 'chageFromManageList'
      if (this.pageState.single_sku) { routeName = 'SKUManageList' }
      if (this.pageState.single_spu) { routeName = 'SPUManageList' }
      this.$router.push({ name: routeName });
    },
    /* 初始化页面数据 */
    initPageDataFn () {
      let { recordNo, uuid, skuNo, type } = this.$route.query;
      if (!type && recordNo) {
        // 如果有单据号，但是没有type值，说明是从OA跳过来的查看页面
        type = 'view';
      }
      let pageType = type || 'menu';
      this.pageState[pageType] = true;
      if (!type) {
        return false;
      } // 如果没有type，表明是菜单页面，无需调用下面的逻辑方法
      this.recordNo = recordNo || '';
      let params = {
        recordNo,
        uuid,
        type,
        skuNo,
        apiSourceList: this.apiSourceList,
        commitType: 'allManaging',
        getExistTableDataAction: this.getExistTableDataAction,
        initQueryExistRecordAction: () => {}
      };
      this.getFieldsInfo(recordNo);
      performDifferentTypeMethodsFn(params);
    },
    /* 获取已存在的表格数据方法 - 表单管理页面，SPU和SKU管理页面进入时调用，菜单界面的修改SKU不调用 */
    getExistTableDataAction (data) {
      let { api, params } = data;
      this.loading.table = true;
      // 开始请求列表
      ApiRequest(api.url, api.type, params, true).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') { return false }
        res.retData.forEach((row) => {
          row.uuid = row.productUuid; // 关联商品是以uuid为标识的，这里返回的表格数据没有uuid参数，只有productUuid，所以代替
          this.ASSOCIATED_GOODS({ row });
        });
        this.initTableDataFn(res.retData);
      }).catch(() => {
        this.loading.table = false;
      });
    },
    /* 初始化表格数据 */
    initTableDataFn (dataSource) {
      this.tableColumns = _.cloneDeep(this.initTableColumns);
      this.tableData = [];
      this.handleDealTableTh(dataSource);
      if (this.pageState.view) {
        return false;
      }
      this.tableColumns.push({
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right'
      });
    },
    /* 获取表格children格式的数据 */
    getChildrenFn (thItem) {
      let children = [
        {
          title: '原值',
          align: 'center',
          render: (h, { row }) => {
            return <div>{row[thItem.attrUuid].valueName}</div>;
          }
        }
      ];
      if (this.pageState.view) {
        children.push({
          title: '现值',
          align: 'center',
          render: (h, { row }) => {
            return generateHighlightNodeForSalePrice(h, row[thItem.attrUuid].valueName, row[thItem.attrUuid].valueNameUpdate)
          }
        });
      } else {
        children.push({
          title: '现值',
          key: thItem.attrUuid,
          align: 'center',
          type: getAttributeTypeFn(thItem.attrType),
          disabled: thItem.canEdit === 'N' || false,
          width: thItem.attrType === '04' ? '180' : '140'
        });
      }
      return children;
    },
    /* 处理表头方法 */
    handleDealTableTh (dataSource) {
      this.tableData = dataSource.reduce((value, item, index) => {
        let {
          productUuid,
          productNameFinal,
          spuNo,
          authDepartments,
          thirdPlatList,
          cityList
        } = item;
        value.push({
          productUuid,
          productNameFinal,
          spuNo,
          authDepartments,
          thirdPlatList,
          cityList
        });
        const nameList = Object.keys(item);
        const notForEachName = ['authDepartments', 'thirdPlatList', 'cityList'];
        nameList.forEach((nameType) => {
          if (!_.isArray(item[nameType]) || notForEachName.includes(nameType)) {
            return false;
          }
          value[index][nameType] = [];
          item[nameType].forEach((thItem) => {
            if (thItem.attrType === '04') {
              thItem.valueNameUpdate = thItem.valueNameUpdate
                ? _.clone(thItem.valueNameUpdate).split(/,|，|\s+/)
                : []; // 以中英文逗号、空格（一个或多个）分割字符串
            }
            value[index][thItem.attrUuid] = thItem;
            value[index][nameType].push(thItem.attrUuid);
            if (
              index === 0 &&
              !this.notShowAttrList.includes(thItem.attrUuid)
            ) {
              this.tableColumns.push({
                title: thItem.attrName,
                align: 'center',
                required: thItem.attrMust === '1' || false,
                children: this.getChildrenFn(thItem)
              });
            }
          });
        });
        return value;
      }, []);
    },
    /* 选择管理区域的下拉事件方法 */
    chooseManageAreaAction (data) {
      const { row, val } = data;
      const target = _.find(row.manage_area.allValueOptions, (item) => {
        return item.optionHtml === val;
      });
      const params = [
        {
          uuid: row.productUuid,
          manageAreaId: target.optionValue
        }
      ];
      this.loading.table = true;
      ApiRequest('/sysback/srm/getDepartments', 'post', params).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') {
          return false;
        }
        row.authDepartments = res.retData[row.productUuid];
      }).catch(() => {
        this.loading.table = false;
      });
    },
    /* 据归类UUID，查询税类代码taxCateNo、销售税率taxRate */
    getTaxInfoDataAction (data) {
      let { allValueOptions, val } = data;
      let target = _.find(allValueOptions, (item) => {
        return item.optionHtml === val;
      });
      let uuid = target.optionValue;
      let params = { uuid };
      return new Promise((resolve, reject) => {
        this.loading.table = true;
        ApiRequest(
          `/sysback/addsingleproduct/basicinfo/getClassificationByUuid?uuid=${uuid}`,
          'post',
          params
        ).then((res) => {
          this.loading.table = false;
          if (res.retStatus !== '1') {
            resolve(false);
            return false;
          }
          let data = {
            taxCateNo: res.retData.taxCateNo,
            taxRate: res.retData.taxRate
          };
          resolve(data);
        }).catch(() => {
          this.loading.table = false;
        });
      });
    },
    /* 处理单选下拉逻辑 */
    handleChangeRadio (data) {
      let { row, val, columnName } = data;
      if (columnName === 'manage_area') {
        // 如果当前切换的是管理区域字段，就调用管理区域接口
        this.chooseManageAreaAction(data);
      } else if (columnName === 'manage_season_product') {
        this.handleChooseManageSeasonProduct(data);
      } else if (columnName === 'tax_classify') {
        // 如果当前切换的是归类名称字段，就调用归类信息接口
        this.getTaxInfoDataAction({
          val,
          allValueOptions: row.tax_classify.allValueOptions
        }).then((res) => {
          if (!res) {
            return;
          }
          row.tax_code.valueNameUpdate = res.taxCateNo;
          row.tax_rate.valueNameUpdate = res.taxRate;
        });
      } else {
        return false;
      }
    },
    /* 处理多选下拉逻辑 */
    handleChangeCheckBox (data) {
      const { row, val, columnName } = data;
      if (columnName !== 'marketing_saleplat') {
        return false;
      }
      const notSaleFlag = val.includes('不销售');
      const notSaleIndex = val.indexOf('不销售');
      if (notSaleFlag) {
        if (val.length === notSaleIndex + 1) {
          row[columnName].valueNameUpdate = ['不销售'];
        } else {
          row[columnName].valueNameUpdate.splice(notSaleIndex, 1);
        }
      } else {
        row[columnName].valueNameUpdate = val;
      }
    },
    /* 高级关联事件 */
    handleSeniorAssociated () {
      const curBtnId = getBtnsId('高级关联');
      sessionStorage.setItem('buttonId', curBtnId);
      this.seniorAssociated.visible = true;
    },
    /* 获取高级关联结果方法 */
    getSeniorResultFn (data) {
      this.seniorAssociated.isSenior = true;
      this.CLEAR_GOODS();
      const url = '/sysback/update/product/allmanaging/queryAllManagingList?multipart=1';
      this.getTableDataAction(data, url);
    },
    /* 点击关联商品的事件 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.CHANGE_MODAL_SWITCH(true);
    },
    /* 获取关联商品后的表格数据的方法 */
    handleGetTableData () {
      const uuidList = this.getListFromMapFn().map((value) => {
        return value.uuid;
      });
      this.seniorAssociated.isSenior = false;
      if (uuidList.length === 0) {
        this.tableData = [];
        return false;
      }
      this.getTableDataAction(uuidList);
    },
    /* 获取表格数据action */
    getTableDataAction (data, requestUrl) {
      const defaultUrl = '/sysback/update/product/allmanaging/queryAllManagingList';
      const url = requestUrl || defaultUrl;
      this.loading.table = true;
      ApiRequest(url, 'post', data, false).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') {
          return false;
        }
        this.initTableDataFn(res.retData);
      }).catch(() => {
        this.loading.table = false;
      });
    },
    /* 删除表格对应行的方法 */
    handleCancelSelect (data) {
      let { row } = data;
      this.tableData = this.tableData.filter(item => row.productUuid !== item.productUuid);
      if (!this.seniorAssociated.isSenior) {
        this.CANCEL_GOODS({ row, type: 'productUuid' });
      }
    },
    /* 暂存 */
    handleSaveData () {
      if (this.tableData.length > EDIT_MANAGE_INFO_AMOUNT) {
        return this.$message.warning(
          `当前单据提交的行数不能超过${EDIT_MANAGE_INFO_AMOUNT}`
        );
      }
      const { submitResults, errorMessage } = getDealManageDataToApiFn({
        tableData: this.tableData,
        notShowAttrList: this.notShowAttrList
      });
      if (errorMessage) {
        return this.$message.warning(errorMessage);
      }
      const { url, type } = this.apiObj.saveBasicInfo;
      const data = {
        recordNo: this.recordNo,
        inputList: submitResults,
        launchReason: this.launchReason // 发起原因
      };
      this.loading.submit = true;
      return new Promise((resolve, reject) => {
        ApiRequest(url, type, data, false).then((res) => {
          this.loading.submit = false;
          if (res.retStatus !== '1') {
            resolve(false);
            return false;
          }
          this.$message.success('保存成功');
          this.recordNo = res.retData.recordNo;
          resolve(true);
        }).catch(() => {
          this.loading.submit = false;
        });
      });
    },
    /* 提交Action */
    submitDataAction () {
      this.handleSaveData().then((res) => {
        if (!res) {
          return false;
        }
        let { url, type } = this.apiObj.commitBasicInfo;
        this.loading.submit = true;
        let authDepartmentList = this.tableData.reduce((value, item) => {
          value.push({
            authDepartments: item.authDepartments
          });
          return value;
        }, []);
        ApiRequest(
          `${url}?recordNo=${this.recordNo}`,
          type,
          authDepartmentList,
          false
        ).then((res) => {
          this.loading.submit = false;
          if (res.retStatus !== '1') {
            return false;
          }
          this.$message.success('提交成功');
          this.$router.push({ name: 'chageFromManageList' });
        }).catch(() => {
          this.loading.submit = false;
        });
      });
    },
    /* 提交的方法 */
    handleSubmitData () {
      this.$Modal.confirm({
        title: '提示',
        content: '确认提交信息吗？',
        onOk: () => {
          this.submitDataAction();
        }
      });
    },
    /* 导出数据 */
    handleExportData () {
      const { submitResults } = getDealManageDataToApiFn({
        tableData: this.tableData,
        notShowAttrList: this.notShowAttrList
      });
      const { url, type } = this.apiObj.exportPageToExcelPost;
      const seniorUrl = `${url}?multipart=1`;
      const exportUrl = this.seniorAssociated.isSenior ? seniorUrl : url;
      this.loading.export = true;
      ApiRequestExportTable(exportUrl, type, submitResults, false).then((res) => {
        this.loading.export = false;
        const blob = new Blob([res], {
          type: 'application/octet-stream'
        });
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = '修改管理信息.xlsx';
        link.click();
        window.URL.revokeObjectURL(blob); // 释放掉blob对象
      }).catch(() => {
        this.loading.export = false;
        this.$Message.error('导出失败');
      });
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.loading.table = true;
      this.tableData = [];
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.loading.table = false;
      this.$message.error('格式错误');
    },
    /* 上传成功 */
    handleUploadSuccess (res) {
      this.loading.table = false;
      if (res.retStatus === '1') {
        // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
        this.initTableDataFn(res.retData);
      } else {
        // 如果接口返回失败,就打印失败信息
        this.$message.error(res.retMessage);
      }
    },
    /* 上传失败 */
    handleUploadError () {
      this.loading.table = false;
      this.$message.error('上传失败');
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
